<template>
  <div class="app-container">
    <el-form :model="skillsForm" :rules="rules" ref="formRef" label-width="140px">
      <el-form-item label="技能标题" prop="title">
        <el-input v-model="skillsForm.title" placeholder="请输入技能标题"></el-input>
      </el-form-item>

      <el-form-item label="技能封面图">
        <el-upload name="file" list-type="picture-card"  :limit="1"
                   :action="uploadImgAddress"
                   :headers="uploadHeaders"
                   :on-success="imgSuccess"
                   :file-list="imgList"
                   :on-exceed="imgHandleExceed">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="技能视频">
        <div class="upload-video">
          <el-upload name="file" class="video-uploader" accept=".mp4,.avi,.mov"
                     :action="uploadVideoAddress" :headers="uploadHeaders"
                     :before-upload="beforeUploadVideo" :on-success="videoSuccess"
                     :on-error="videoError" :show-file-list="true"
          >
            <!-- 显示上传的视频或上传按钮 -->
            <video v-if="videoUrl" :src="videoUrl" class="video-preview" controls/>
            <el-button v-else type="primary">
              <i class="el-icon-upload"></i> 上传视频
            </el-button>

            <!-- 显示提示信息 -->
            <div class="upload-tip" slot="tip">
              <p>支持格式：MP4、AVI、MOV</p>
              <p>文件大小不超过500MB</p>
            </div>
          </el-upload>

          <!-- 上传进度条 -->
          <el-progress
            v-if="uploadProgress > 0 && uploadProgress < 100"
            :percentage="uploadProgress"
            :stroke-width="4"
          ></el-progress>
        </div>
      </el-form-item>

      <el-form-item label="技能类型" prop="type">
        <el-select  v-model="skillsForm.type" placeholder="请选择技能类型">
          <el-option v-for="item in skillsTypeOptions" :key="item.dictValue" :value="item.dictValue" :label="item.dictLabel"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="考试题数" prop="examNum">
        <el-input v-model="skillsForm.examNum" type="number" placeholder="请输入考试题数" style="width: 202px"></el-input>
      </el-form-item>

      <el-form-item label="周期学习"  prop="cycle">
        <el-radio v-model="skillsForm.cycle" :label="false" :disabled="skillsId !==''">否</el-radio>
        <el-radio v-model="skillsForm.cycle" :label="true" :disabled="skillsId !==''">是</el-radio>
      </el-form-item>

<!--      <el-form-item label="是否必学" prop="mustLearn">-->
<!--        <el-radio v-model="skillsForm.mustLearn" :label="false">否</el-radio>-->
<!--        <el-radio v-model="skillsForm.mustLearn" :label="true">是</el-radio>-->
<!--      </el-form-item>-->

      <el-form-item label="内容" prop="content">
        <template>
          <div style="border: 1px solid #ccc;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden;"
              v-model="skillsForm.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
            />
          </div>
        </template>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import { getStudySkillsById,editSkills } from '@/api/regulatory/studySkills'
  import { getToken } from '@/utils/auth'

  export default {
    name : "editSkills",
    props: ["skillsId"],
    components: {Toolbar, Editor},
    data()  {
      return {
        skillsTypeOptions:[], //技能类型下拉框
        skillsForm : { //表单内容
          id: null,
          title:'',
          img:'',
          video:'',
          type:'',
          examNum : 0,
          cycle: false,
          mustLearn: false,
          content:'',
        },
        uploadImgAddress : process.env.VUE_APP_BASE_API+'/studySkills/uploadSkillsPhoto' , //图片上传地址
        uploadVideoAddress : process.env.VUE_APP_BASE_API+'/studySkills/uploadSkillsVideo' , //视频上传地址
        uploadHeaders:{ //上传文件头部
          Authorization: "Bearer "+getToken()
        },
        imgList:[], //封面图列表
        videoUrl: '', //视频地址
        uploadProgress: 0, //视频上传进度

        editor: null, //富文本
        toolbarConfig: { }, //富文本工具栏配置
        editorConfig: { //富文本编辑器配置
          placeholder: '请输入内容...',
          MENU_CONF:{
            uploadImage:{
              fieldName: 'file', // 自定义上传字段名
              maxFileSize: 10 * 1024 * 1024, //限制图片大小最大为10M
              server: process.env.VUE_APP_BASE_API+'/studySkills/uploadSkillsPhoto', //上传图片的接口地址
              maxNumberOfFiles: 3, //最多可上传3个文件
              timeout: 5 * 1000, // 5 秒超时
              headers: {
                Authorization: 'Bearer ' + getToken()
              },
              customInsert(res, insertFn){
                console.log(res)
                insertFn(res.data)  // 插入图片
              },
            }
          }
        },
        mode: 'default', // 富文本默认配置模式

        rules: { //表单验证
          title: [
            {required: true, message: '请输入技能标题', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请选择技能类型', trigger: 'change'}
          ],
          cycle: [
            {required: true, message: '请选择周期学习', trigger: 'change'}
          ],
          content: [
            {required: true, message: '请输入技能内容', trigger: 'blur'}
          ]
        },
      }
    },
    created() {
      //技能类型下拉框赋值
      this.getDicts("knowledge_type").then(response => {
        this.skillsTypeOptions = response.data;
      })

      //编辑查询技能数据
      if(this.skillsId !=='') {
        getStudySkillsById(this.skillsId).then(response => {
          this.skillsForm = response.data
          this.skillsForm.type = String(this.skillsForm.type)
          this.imgList = [{ url: response.data.img}]
          this.videoUrl =  response.data.video
        })
      }
    },
    methods : {
      //图片上传成功回调
      imgSuccess(res) {
        this.skillsForm.img = res.data
        this.$message.success('上传成功！')
      },
      //文件超出个数限制时的钩子
      imgHandleExceed(){
        this.$message.error("只能上传一张图片")
      },
      //视频上传检查
      beforeUploadVideo(file) {
        // 文件类型检查
        const isVideo = file.type.indexOf('video') !== -1
        if (!isVideo) {
          this.$message.error('请上传视频文件！')
          return false
        }
        // 文件大小检查
        const isLtMax = file.size / 1024 / 1024 < 500
        if (!isLtMax) {
          this.$message.error(`视频大小不能超过500MB！`)
          return false
        }
        return true
      },
      //视频上传成功回调
      videoSuccess(res, file) {
        this.videoUrl = URL.createObjectURL(file.raw)
        this.uploadProgress = 100
        this.skillsForm.video = res.data
        this.$message.success('上传成功！')
      },
      //视频上传失败回调
      videoError(err, file) {
        this.uploadProgress = 0
        console.log("上传失败"+err)
        console.log('文件信息:', file)
        this.$message.error('上传失败，请重试！')
      },

      //富文本创建
      onCreated(editor) {
        this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      },

      //表单提交
      submitForm() {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            editSkills(this.skillsForm).then(()=> {
              this.$message.success('保存成功！');
              this.$emit('editSkillsSuccess');
            })
          }
        });
      },
    }
  }
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.upload-video {
  width: 100%;
  max-width: 600px;
}

.video-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  padding: 20px;
}

.video-uploader:hover {
  border-color: #409EFF;
}

.video-preview {
  width: 100%;
  max-height: 300px;
  object-fit: contain;
}

.upload-tip {
  color: #666;
  font-size: 12px;
  margin-top: 10px;
}
</style>
